package com.example.technologia;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

public class MyService extends Service {

	private Toast toast;
	private Timer timer;
	private TimerTask timerTask;
	private float down;
	private float up;
	private int milis;
	private String currency;

	private class MyTimerTask extends TimerTask {
		@Override
		public void run() {
			getBitcoinValue();
		}
	}

	private final Handler notifyUser = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Toast.makeText(MyService.this, msg.getData().getString("MSG"),
					Toast.LENGTH_LONG).show();
			// Vibrate the mobile phone
			Vibrator vibrator = (Vibrator) MyService.this
					.getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(2000);

			Intent resultIntent = new Intent(MyService.this, MainActivity.class);
			// Because clicking the notification opens a new ("special")
			// activity, there's
			// no need to create an artificial back stack.
			PendingIntent resultPendingIntent = PendingIntent.getActivity(
					MyService.this, 0, resultIntent,
					PendingIntent.FLAG_UPDATE_CURRENT);

			// Define sound URI
			Uri soundUri = RingtoneManager
					.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

			NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
					MyService.this).setSmallIcon(R.drawable.ic_launcher)
					.setContentTitle("Bitcoin")
					.setContentText(msg.getData().getString("MSG"))
					.setSound(soundUri)
					.setVibrate(new long[] { 100, 500, 100, 200 })
					.setContentIntent(resultPendingIntent);

			int mNotificationId = 001;
			// Gets an instance of the NotificationManager service
			NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			// Builds the notification and issues it.
			mNotifyMgr.notify(mNotificationId, mBuilder.build());
		}
	};

	@Override
	public void onCreate() {
		super.onCreate();
		timer = new Timer();
	}

	private void clearTimerSchedule() {
		if (timerTask != null) {
			timerTask.cancel();
			timer.purge();
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		currency = intent.getStringExtra("com.example.technologia.CURRENCY");
		down = Float.parseFloat(intent
				.getStringExtra("com.example.technologia.DOWN"));
		up = Float.parseFloat(intent
				.getStringExtra("com.example.technologia.UP"));
		milis = Integer.parseInt(intent
				.getStringExtra("com.example.technologia.TIME")) * 1000 * 60;
		clearTimerSchedule();
		timerTask = new MyTimerTask();
		timer.scheduleAtFixedRate(timerTask, milis, milis);
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		clearTimerSchedule();
		super.onDestroy();
	}

	private void getBitcoinValue() {
		try {
			InputStream content = null;
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(new HttpGet(
					"http://blockchain.info/pl/tobtc?currency=" + currency
							+ "&value=" + 10000));
			content = response.getEntity().getContent();
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					content));
			String value = rd.readLine();
			float valueFloat = Float.parseFloat(value);
			if (valueFloat < down || valueFloat > up) {
				Bundle b = new Bundle();
				b.putString("MSG", "You should go to cantor, value: " + value);
				Message m = new Message();
				m.setData(b);
				notifyUser.sendMessage(m);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Bundle b = new Bundle();
			b.putString("MSG", e.getMessage());
			Message m = new Message();
			m.setData(b);
			notifyUser.sendMessage(m);
			stopSelf();
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}
